using UnityEngine;

public class Enemy : MonoBehaviour
{
    enum State
    { Follow, Attack }
    public GameObject enemyBullet;
    public float speed = 3;
    private State state;

    public float followSeconds = 3;
    public float attackSeconds = 1;
    private float timer;

    public float attackInterval = 0.1f;
    public float attackTimer = 0;

    public SpriteRenderer sprite;
    private Rigidbody2D rb;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        timer += Time.deltaTime;
        switch (state)
        {
            case State.Follow:
                {
                    if (Global.player != null)
                    {
                        Vector3 dir = Global.player.transform.position - transform.position;
                        // transform.Translate(dir.normalized * speed * Time.deltaTime);
                        rb.velocity = dir.normalized * speed;
                        if (dir.x < 0)
                        {
                            sprite.flipX = true;
                        }
                        else
                        {
                            sprite.flipX = false;
                        }
                        if (timer > followSeconds)
                        {
                            timer = 0;
                            state = State.Attack;
                            attackSeconds = Random.Range(5, 20) * 0.1f;
                        }
                    }
                }
                break;
            case State.Attack:
                {
                    if (timer > attackSeconds)
                    {
                        timer = 0;
                        state = State.Follow;
                        followSeconds = Random.Range(5, 30) * 0.1f;
                    }
                    else
                    {
                        attackTimer += Time.deltaTime;
                        if (attackTimer > attackInterval)
                        {
                            attackTimer = 0;
                            Vector3 dir = Global.player.transform.position - transform.position;
                            Fire(dir.normalized);
                        }
                    }
                }
                break;
        }
    }

    public void Fire(Vector3 direction)
    {
        // 创建子弹
        GameObject bullet = Instantiate(enemyBullet);
        bullet.gameObject.SetActive(true);
        // 设置子弹的位置
        bullet.transform.position = transform.position;
        // 设置子弹的速度
        bullet.GetComponent<EnemyBullet>().direcition = direction;
    }
}
